package com.mage.myshop.service;

import com.mage.myshop.model.Category;
import freemarker.template.SimpleNumber;
import org.springframework.stereotype.Service;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CategoryService {

    private List<Category> categories = new ArrayList<>();

    public CategoryService () {
        // 获取文件路径
        Path path = Paths.get("src/main/data/categories");
        try {
            // 读取文件所有行
            List<String> lines =  Files.readAllLines(path);
            lines.remove(0);
            lines.forEach(line -> {
                String[] data = line.split(",");
                Integer parentId = null;
                if (!"NULL".equals(data[3].trim())) {
                    parentId = Integer.parseInt(data[3].trim());
                }
                Category category = new Category(Integer.parseInt(data[0].trim()), data[1].trim(),
                        Integer.parseInt(data[2].trim()), parentId);
                categories.add(category);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Category> getCategories() {
        return categories;
    }

    public List<Category> findRoot() {
//        List<Category> root = new ArrayList<>();
//        for (Category category : categories) {
//            if (category.getParentId() == null) {
//                root.add(category);
//            }
//        }
        List<Category> root = this.categories.stream()
                .filter(c -> c.getParentId() == null).limit(6)
                .collect(Collectors.toList());
        return root;
    }

    public List<Category> findChildren(int parentId, SimpleNumber limit) {
        List<Category> children = null;
        Stream<Category> stream = this.categories.stream()
                .filter(c -> c.getParentId() != null)
                .filter(c -> c.getParentId() == parentId);
        if (limit == null) {
            children = stream.collect(Collectors.toList());
        } else {
           children = this.categories.stream().limit(limit.getAsNumber().intValue())
                    .collect(Collectors.toList());
        }
        return children;
    }
}
